package main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

func main_server() error {
	// 获取执行文件的绝对路径
	iniExePath()
	err2 := CheckProcessExists()
	if err2 != nil {
		log.Println("CheckProcessExists=>", runFileServer, ":", err2)
		_, err := os.Stat(execNamePath + "/" + runFileServer)
		if !os.IsNotExist(err) {
			return runProcess()
		} else {
			log.Println("执行文件名不存在:", execNamePath+"/"+runFileServer)
		}

	}

	return nil
}

// CheckProcessExists 检测进程是否存在 ,存在 返回"" ,不存在，可以启动返回 可启动文件名
func CheckProcessExists() error {
	var cmd *exec.Cmd
	// 根据操作系统选择命令
	// 进程判断
	runFileServerc := runFileServer

	switch runtime.GOOS {
	case "windows":
		cmd = exec.Command("tasklist", "/FI", "IMAGENAME eq "+runFileServer)
		// window进程名称不能超过25
		if len(runFileServerc) > 25 {
			runFileServerc = runFileServerc[0:25]
		}
	case "linux":

		cmd = exec.Command("ps", "-C", runFileServer)
		// linux 进程名称不能超过15
		if len(runFileServerc) > 15 {
			runFileServerc = runFileServerc[0:15]
		}
	default:
		return errors.New("系统不支持")
	}
	// 执行命令并获取输出
	output, err := cmd.Output()
	if err != nil {
		return err
	}

	// 判断输出中是否包含进程名
	if strings.Contains(string(output), runFileServerc) {
		return nil
	}

	return errors.New("not run" + runFileServerc + "=" + string(output))
}

// 启动其他程序
func runProcess() error {
	iniExePath()

	var cmd *exec.Cmd

	switch runtime.GOOS {
	case "windows":
		// 在 Windows 中，使用 cmd.exe 来执行命令
		cmd = exec.Command("cmd.exe", "/C", "cd", execNamePath, "&&", runFileServer)

	case "linux":
		// 在 Linux 中，使用 sh 来执行命令
		cmd = exec.Command("sh", "-c", fmt.Sprintf("cd %s && ./%s", execNamePath, runFileServer))

	default:
		return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
	}
	fmt.Errorf("cmd.Run()")
	// 启动进程
	return cmd.Start()
}

// 结束其他程序
func stopProcess() error {
	iniExePath()
	if runFileServer == "" {
		return errors.New("runFileServer kong")
	}
	var cmd *exec.Cmd

	switch runtime.GOOS {
	case "windows":
		// 执行重启
		cmdLine := fmt.Sprintf(`taskkill /f /t /im %s&exit`, runFileServer)
		//cmd = exec.Command("taskkill", "/f", "/t", "/im", runFileServer)
		filePath := execNamePath + "/serviceRestart.bat"
		err := writeStringFile(filePath, cmdLine)
		if err != nil {
			return err
		}
		cmd = exec.Command("cmd.exe", "/c", "start serviceRestart.bat")
		err = cmd.Run()
		time.Sleep(1 * time.Second)
		// 删除文件
		os.Remove(filePath)
		return err
	case "linux":
		cmdLine := fmt.Sprintf("pkill %s;killall -9 %s;", runFileServer, runFileServer)
		cmd = exec.Command("sh", "-c", cmdLine)
		return cmd.Run()
	default:

	}

	return nil
}
func writeStringFile(filename string, content string) error {

	os.MkdirAll(filepath.Dir(filename), os.ModePerm)
	// 打开文件，如果文件不存在则创建新文件
	file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		return err
	}
	defer file.Close()

	// 写入文件内容
	_, err = file.WriteString(content)
	if err != nil {
		return err
	}

	// 将缓冲区的内容写入磁盘
	err = file.Sync()
	if err != nil {
		return err
	}
	return nil
}
